package com.tingyu.blog.service;

import com.tingyu.blog.MyNotFoundException;
import com.tingyu.blog.dao.TypeRepository;
import com.tingyu.blog.po.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class TypeServiceImpl implements TypeService {
    @Autowired
    private TypeRepository typeRepository;


    @Transactional
    @Override
    /**
     * 添加分类
     * @param 分类对象(Type type)
     * @return 添加的分类对象
     */
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    @Transactional
    @Override
    /***
     * 查询一个分类
     * @param id
     */
    public Type getOneType(int id) {
        return typeRepository.getOne(id);
    }


    @Override
    public Type getOneTypeByName(String name) {
        return typeRepository.findByName(name);
    }

    @Transactional
    @Override
    /**
     * 分页查询
     * @param pageable
     */
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    /**
     * 分类列表根据博客数量倒序后取前几条
     * @param size
     * @return
     */
    @Override
    public List<Type> listTypeTop(int size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return typeRepository.findTop(pageable);
    }

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    @Transactional
    @Override
    /**
     * 编辑、修改分类
     * @param id,type对象
     * @return 返回修改、更新后的type对象
     */
    public Type editType(int id, Type type) {
        Type t = typeRepository.getOne(id);
        if (t == null){
            throw new MyNotFoundException("该分类不存在！");
        }
        BeanUtils.copyProperties(type,t);   //用type对象覆盖t对象
        return typeRepository.save(t);      //通过覆盖t对象内容已更新
    }

    @Transactional
    @Override
    /**
     * 删除分类
     * @param  int id
     */
    public void deleteType(int id) {
        typeRepository.deleteById(id);
    }
}
